package com.sakura.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakura.oj.mapper.ProblemTagMapper;
import com.sakura.oj.model.entity.ProblemTag;
import com.sakura.oj.model.entity.Tag;
import com.sakura.oj.service.ProblemTagService;
import com.sakura.oj.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProblemTagServiceImpl extends ServiceImpl<ProblemTagMapper, ProblemTag> implements ProblemTagService {

    @Resource
    private TagService tagService;

    /**
     * 根据标签ID列表获取题目ID列表
     *
     * @param tagIdList 标签ID列表
     * @return 题目ID列表
     */
    @Override
    public List<Long> getProblemIdListByTagIds(List<Integer> tagIdList) {
        if (tagIdList == null || tagIdList.isEmpty()) {
            return null;
        }

        // 查询所有符合条件的题目标签关联
        QueryWrapper<ProblemTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("tag_id", tagIdList);
        List<ProblemTag> problemTagList = this.list(queryWrapper);

        // 提取题目ID并去重
        return problemTagList.stream()
                .map(ProblemTag::getProblemId)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<Tag> listByProblemId(Long id) {
        LambdaQueryWrapper<ProblemTag> queryWrapper = new LambdaQueryWrapper<ProblemTag>()
                .eq(ProblemTag::getProblemId, id);

        List<ProblemTag> problemTagList = list(queryWrapper);
        if (problemTagList != null) {
            List<Long> tagIdList = problemTagList.stream().map(ProblemTag::getTagId).collect(Collectors.toList());
            if (CollUtil.isEmpty(tagIdList)) return List.of();
            // 根据tagIdList查询标签
            return tagService.listByIds(tagIdList);
        }
        return List.of();
    }

}
